<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
    <title>Title</title>
    <link th:href="@{/layui/css/layui.css}" rel="stylesheet" />
</head>
<body class="layui-layout-body">


<div class="layui-btn-container">
    <button type="button" class="layui-btn layui-btn-sm" id="add-user">新增</button>
</div>
<table id="log-table" lay-filter="test-log"></table>

<script th:src="@{/layui/layui.js}"></script>
<script th:src="@{/js/utils.js}"></script>
<script th:src="@{/js/token_filter.js}"></script>
<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
<script>

    layui.use('table', function() {
        let $ = layui.$;
        $(function(){
            ct();
            let token = layui.data("tokens").token;
            let table = layui.table;
            //第一个实例
            table.render({
                elem: '#log-table'
                ,method:"POST"
                ,url: 'https://common.mengqizhang.xyz/system/user/list' //数据接口
                ,page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                    layout: ['limit','limits', 'count', 'prev','page','next', 'first','last','skip'] //自定义分页布局
                    ,limit:20
                    ,limits:[5,10,15,20]
                    ,groups: 5 //只显示 5 个连续页码
                }
                ,request:{
                    pageName:"pageCurrent",
                    limitName:"pageSize"
                }
                ,contentType:"application/json;charset=UTF-8"
                ,response: {
                    statusCode: 200 //重新规定成功的状态码为 200，table 组件默认为 0
                }
                ,id:"roleTable"
                ,headers: {token:token}
                ,cols: [
                    [
                        {field: 'id', title: 'ID', sort: true, fixed: 'left'}
                        ,{field: 'enable', title: '启用标识'}
                        ,{field: 'loginName', title: '登录账号',  sort: true}
                        ,{field: 'name', title: '用户名称'}
                        ,{field: 'roleId', title: '角色id'}
                        ,{field: 'roleName', title: '角色名称', sort: true}
                        ,{fixed: 'right', title:'操作', toolbar: '#barDemo', width:150}
                    ]
                ]
                ,parseData:function(data){
                    return {
                        "code": data.code, //解析接口状态
                        "msg": data.msg, //解析提示文本
                        "count": data.data.total, //解析数据长度
                        "data": data.data.records //解析数据列表
                    };
                }
            });


            //头工具栏事件
            table.on('toolbar(test-log)', function(obj){
                console.log(obj);
                var checkStatus = table.checkStatus(obj.config.id);
                switch(obj.event){
                    case 'getCheckData':
                        var data = checkStatus.data;
                        layer.alert(JSON.stringify(data));
                        break;
                    case 'getCheckLength':
                        var data = checkStatus.data;
                        layer.msg('选中了：'+ data.length + ' 个');
                        break;
                    case 'isAll':
                        layer.msg(checkStatus.isAll ? '全选': '未全选');
                        break;

                    //自定义头工具栏右侧图标 - 提示
                    case 'LAYTABLE_TIPS':
                        layer.alert('这是工具栏右侧自定义的一个图标按钮');
                        break;
                };
            });

            $("#add-user").on("click",function(){

                layer.open({
                    type: 2, //Layer提供了5种层类型。可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）,
                    title: 'title here',   //标题
                    area: ['650px', '600px'],   //宽高
                    shade: 0.4,   //遮罩透明度
                    content:"https://common.mengqizhang.xyz/index/system/userSave",//支持获取DOM元素
                    btn: ['确定', '取消'], //按钮组
                    scrollbar: false ,//屏蔽浏览器滚动条
                    success:function(layero,index){
                        // 获取子页面的iframe
                        let iframe = window['layui-layer-iframe' + index];
                        // 向子页面的全局函数child传参
                        iframe.init(null);

                    },
                    yes: function(index,layero){//layer.msg('yes');    //点击确定回调
                        let iframeWin = window[layero.find('iframe')[0]['name']];//得到iframe页的窗口对象，执行iframe页的方法：
                        let result = iframeWin.getCheckedForParent();
                        if(result == null || result.length==0){
                            layer.msg("请选择角色权限！");
                            return false;
                        }
                        let r;
                        if(result.charAt(result.length-1)==","){
                            r = result.substring(0,result.length-1);
                        }
                        let ids = r.split(",");
                        console.log(ids);
                        let sId = iframeWin.document.getElementById("id").value;
                        let sName = iframeWin.document.getElementById("name").value;
                        let sNo = iframeWin.document.getElementById("no").value;
                        let data = {
                            "id":sId,
                            "name":sName,
                            "no":sNo,
                            "ids":ids
                        };

                        layui.$.ajax({
                            url:"https://common.mengqizhang.xyz/system/role/save",
                            data:JSON.stringify(data),
                            type:"POST",
                            async:false,
                            headers:{'Accept':'application/json','token':token},
                            dataType:"JSON",
                            contentType:"application/json;charset=UTF-8",
                            success:function(data){
                                let code = data.code;
                                if(code == 200){
                                    //执行重载
                                    //table.reload('roleTable', {});
                                    table.reload("roleTable",function(){
                                        page: {
                                            curr:1 //重新从第 1 页开始
                                        }
                                    });
                                    layer.close(index);
                                }else{
                                    layer.msg(data.msg);
                                }
                            },
                            error:function(data){
                                layui.$.alert('发生未知错误',data.msg);
                            }
                        });
                    }, btn2: function(){//layer.alert('aaa',{title:'msg title'});  ////点击取消回调
                        //layer.msg('bbb');//layer.closeAll();
                    }
                });



            });


            //监听行工具事件
            table.on('tool(test-log)', function(obj){
                let data = obj.data;
                console.log(obj)
                if(obj.event === 'del'){
                    layer.confirm('真的删除行么', function(index){
                        layui.$.ajax({
                            url:"https://common.mengqizhang.xyz/system/user/remove?id="+obj.data.id,
                            data:null,
                            type:"GET",
                            async:false,
                            headers:{'Accept':'application/json','token':token},
                            dataType:"JSON",
                            contentType:"application/json;charset=UTF-8",
                            success:function(data){
                                let code = data.code;
                                if(code == 200){
                                    //执行重载
                                    //table.reload('roleTable', {});
                                    layer.msg(data.msg,function(){
                                        obj.del();
                                        layer.close(index);
                                    });
                                }else{
                                    layer.msg(data.msg);
                                }
                            },
                            error:function(data){
                                layui.msg(data.msg);
                            }
                        });
                    });
                } else if(obj.event === 'edit'){
                    layer.open({
                        type: 2, //Layer提供了5种层类型。可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）,
                        title: 'title here',   //标题
                        area: ['650px', '600px'],   //宽高
                        shade: 0.4,   //遮罩透明度
                        content:"https://common.mengqizhang.xyz/index/system/userSave",//支持获取DOM元素
                        btn: ['确定', '取消'], //按钮组
                        scrollbar: false ,//屏蔽浏览器滚动条
                        success:function(layero,index){
                            // 获取子页面的iframe
                            let iframe = window['layui-layer-iframe' + index];
                            // 向子页面的全局函数child传参
                            iframe.init(obj.data.id);

                        },
                        yes: function(index,layero){//layer.msg('yes');    //点击确定回调
                            let iframeWin = window[layero.find('iframe')[0]['name']];//得到iframe页的窗口对象，执行iframe页的方法：
                            //let ids = iframeWin.sendDataToParent();
                            let result = iframeWin.getCheckedForParent();
                            let r;
                            if(result.charAt(result.length-1)==","){
                                r = result.substring(0,result.length-1);
                            }
                            let ids = r.split(",");
                            console.log(ids);
                            let sId = iframeWin.document.getElementById("id").value;
                            let sName = iframeWin.document.getElementById("loginName").value;
                            let sPassword = iframeWin.document.getElementById("passWord").value;
                            let sRoleId = iframeWin.document.getElementById("roleId").value;
                            let data = {
                                "id":sId,
                                "name":sName,
                                "no":sNo,
                                "ids":ids
                            };


                            return ;
                            layui.$.ajax({
                                url:"https://common.mengqizhang.xyz/system/role/save",
                                data:JSON.stringify(data),
                                type:"POST",
                                async:false,
                                headers:{'Accept':'application/json','token':token},
                                dataType:"JSON",
                                contentType:"application/json;charset=UTF-8",
                                success:function(data){
                                    let code = data.code;
                                    if(code == 200){
                                        //执行重载
                                        //table.reload('roleTable', {});
                                        table.reload("roleTable",function(){
                                            page: {
                                                curr:1 //重新从第 1 页开始
                                            }
                                        });
                                        layer.close(index);
                                    }else{
                                        layer.msg(data.msg);
                                    }
                                },
                                error:function(data){
                                    layui.$.alert('发生未知错误',data.msg);
                                }
                            });
                        }, btn2: function(){//layer.alert('aaa',{title:'msg title'});  ////点击取消回调
                            //layer.msg('bbb');//layer.closeAll();
                        }
                    });
                }
            });
        });
    });

</script>
</body>
</html>